﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.Xml;
using FunnyFace.Common;
using SqlConnectionHandler;
using WebClientPlatform.Models;
using TCSmartFramework.DataAccess;

namespace WebClientPlatform.Controllers
{
    public class HomeController : Controller
    {
        public ActionResult Index()
        {
            ViewBag.Message = "Welcome to ASP.NET MVC!";

            return View(new ConnectionModel() { IsEncrypt = true });
        }


        [HttpPost]
        public ActionResult Index(ConnectionModel model)
        {
            if (ModelState.IsValid)
            {

                try
                {
                    model.ResultText = model.IsEncrypt ? model.Text.Encrypt() : model.Text.Decrypt();
                }
                catch (Exception e)
                {
                    ModelState.AddModelError("", model.IsEncrypt ? "Encrypt" : "Decrypt " + " was unsuccessful. " + e.Message);
                }
            }
            return View(model);
        }



        public ActionResult LoadJsTest()
        {
            return View();
        }


        public ActionResult LoadConfig(string querykey, string filePath)
        {
            if (string.IsNullOrEmpty(filePath))
            {
                const string newFile = "TCSmartFramework.DataAccess.config";
                string baseAddress = Server.MapPath(@"/UploadFile/");
                filePath = Path.Combine(baseAddress, newFile);

            }
            ViewBag.FilePath = filePath;
            ViewBag.QueryKey = querykey;
            IList<DatabaseModel> dbInfos = LoadDatabaseInfo(filePath);
            if (!string.IsNullOrEmpty(querykey))
            {

                dbInfos = dbInfos.Where(e => e.Reads.Any(m => m.ConnectionString.ToLower().Contains(querykey.ToLower()))
                     || e.Writes.Any(m => m.ConnectionString.ToLower().Contains(querykey.ToLower()))).ToList();

            }
            return View(dbInfos);
        }



        public ActionResult LoadFtps()
        {
            IList<FtpModel> ftpModels = GetFtps();
            return View(ftpModels);
        }


        public ActionResult LoadFtpFile(FtpModel model)
        {
            FTPHelper ftp = new FTPHelper(model.IP, model.RemotePath, model.UserId, model.Password);

            string basePath = Server.MapPath("/UploadFile/");
            if (!Directory.Exists(basePath))
            {
                Directory.CreateDirectory(basePath);
            }

            string filePath = basePath + model.FileName;
            if (System.IO.File.Exists(filePath))
            {
                System.IO.File.Delete(filePath);
            }
            ftp.Download(basePath, model.FileName);
            return RedirectToAction("LoadConfig", new { querykey = "", filePath = filePath });
        }




        public ActionResult About()
        {
            return View();
        }



        [HttpPost]
        public ActionResult Upload(FormCollection form)
        {
            if (Request.Files.Count == 0)
            {
                //Request.Files.Count 文件数为0上传不成功
                return View("LoadConfig");
            }

            var file = Request.Files[0];
            string newPath = string.Empty;
            if (file == null || file.ContentLength == 0)
            {
                //文件大小大（以字节为单位）为0时，做一些操作
                return View("LoadConfig");
            }
            else
            {
                //文件大小不为0
                //HttpPostedFileBase file = Request.Files[0];
                //保存成自己的文件全路径,newfile就是你上传后保存的文件,
                //服务器上的UpLoadFile文件夹必须有读写权限　　　　　　
                const string newFile = "TCSmartFramework.DataAccess.config";
                string baseAddress = Server.MapPath(@"/UploadFile/");
                if (!Directory.Exists(baseAddress))
                {
                    Directory.CreateDirectory(baseAddress);
                }
                newPath = Path.Combine(baseAddress, newFile);
                if (System.IO.File.Exists(newFile))
                {
                    System.IO.File.Delete(newFile);
                }
                file.SaveAs(newPath);

            }

            //IList<DatabaseModel> dbInfos = LoadDatabaseInfo(newPath);

            //newFile = DateTime.Now.ToString("yyyyMMddHHmmss") + ".sl";

            return View("LoadConfig");

        }

        static IList<DatabaseModel> DBINFO;


        ServerModel LoadServerInfo(XmlNode nodel)
        {
            ServerModel server = new ServerModel();
            if (nodel.Attributes != null)
            {
                string weight = GetValue(nodel.Attributes["weigth"]);
                server.Weight = string.IsNullOrEmpty(weight) ? 0 : Convert.ToInt32(weight);

                server.Encrypt = GetValue(nodel.Attributes["encrypt"]) == "true";

                server.Enabled = GetValue(nodel.Attributes["enabled"]) == "true";
                server.ConnectionString = server.Encrypt ? nodel.Attributes["connectionString"].Value.Decrypt() : nodel.Attributes["connectionString"].Value;
            }
            return server;

        }


        IList<DatabaseModel> LoadDatabaseInfo(string file)
        {
            IList<DatabaseModel> dbInfos = null;
            XmlNode node = XMLHelper.GetXmlNodeByXpath(file, "TCSmartFramework.DataAccess");
            if (node != null && node.ChildNodes != null)
            {
                dbInfos = new List<DatabaseModel>();
                foreach (XmlNode item in node.ChildNodes)
                {
                    DatabaseModel db = new DatabaseModel();
                    if (item.Attributes != null)
                    {
                        db.Name = item.Attributes["name"].Value;
                        db.IsDefault = GetValue(item.Attributes["default"]) == "true";

                        XmlNodeList servers = item.ChildNodes;
                        IList<ServerModel> reads = new List<ServerModel>();
                        IList<ServerModel> writes = new List<ServerModel>();
                        foreach (XmlNode serverNode in servers)
                        {
                            foreach (XmlNode readNode in serverNode.ChildNodes)
                            {
                                ServerModel serverInfo = LoadServerInfo(readNode);
                                if (serverNode.Name.ToLower() == "read")
                                {
                                    reads.Add(serverInfo);
                                }
                                else
                                {
                                    writes.Add(serverInfo);
                                }
                            }
                        }
                        db.Reads = reads;
                        db.Writes = writes;
                        dbInfos.Add(db);
                    }

                }

            }

            return dbInfos ?? new List<DatabaseModel>();
        }


        private IList<FtpModel> GetFtps()
        {
            IList<FtpModel> ftps = new List<FtpModel>();
            XmlNode node = XMLHelper.GetXmlNodeByXpath(Server.MapPath("/App_Data/FtpInfo.xml"), "ftps");
            if (node != null && node.ChildNodes != null)
            {
                foreach (XmlNode ftp in node.ChildNodes)
                {
                    if (ftp != null && ftp.ChildNodes != null)
                    {
                        FtpModel ftpModel = new FtpModel();
                        foreach (XmlNode item in ftp.ChildNodes)
                        {
                            switch (item.Name)
                            {
                                case "name":
                                    ftpModel.Name = item.InnerText;
                                    break;
                                case "ip":
                                    ftpModel.IP = item.InnerText;
                                    break;
                                case "userid":
                                    ftpModel.UserId = item.InnerText;
                                    break;
                                case "path":
                                    ftpModel.RemotePath = item.InnerText;
                                    break;
                                case "password":
                                    ftpModel.Password = item.InnerText;
                                    break;
                                case "file":
                                    ftpModel.FileName = item.InnerText;
                                    break;
                                case "leader":
                                    ftpModel.Leader = item.InnerText;
                                    break;
                                case "group":
                                    ftpModel.Group = item.InnerText;
                                    break;
                            }
                        }
                        ftps.Add(ftpModel);
                    }
                }
            }
            return ftps;
        }

        string GetValue(XmlAttribute attribute)
        {
            return attribute == null ? string.Empty :
                (string.IsNullOrEmpty(attribute.Value) ? string.Empty : attribute.Value.ToLower());
        }



        public ActionResult ExcuteSQL()
        {
            return View(0);
        }


        [HttpPost]
        public ActionResult ExcuteSQL(string sqlStr)
        {

            int result = SqlHelper.ExecuteNonQuery(sqlStr);
            return View(result);
        }

        

    }
}
